# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

# Allows stubbing the File object to capture file output
# be careful because as the file will not be saved to disk, operations as
# exists? will fail

class FileStub
  attr_accessor :buffer
  def puts(message = nil)
    @buffer ||= ""
    @buffer << "#{message}\n"
  end

  def write(message = nil)
    @buffer ||= ""
    @buffer << "#{message}\n"
  end
  
  def flush
    # do nothing
  end
  
  def to_s
    buffer
  end
end

class Test::Unit::TestCase
  def stub_file 
    begin
      File.class_eval do
        # override the usage of the File object on tests only
        class << self
          alias :old_open :open

          def open(path, mode = nil, perm = nil, &block)
            if path =~ /\.log$/
              @@buffer = FileStub.new
              yield @@buffer
            else
              old_open(path, mode, perm, &block)
            end
          end

          def buffer
            @@buffer.to_s
          end
        end  
      end
      
      yield
    ensure
      File.class_eval do
        class << self
          alias :open :old_open
        end
      end
    end
  end
end